<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-11
 * Time: 14:54
 */

namespace app\common\model;

use app\api\validate\Scheduling;
use app\common\service\AddService;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use think\Db;
use think\Exception;
use think\Model as ThinkModel;
use app\common\service\ProjectService;

//银行列表模型
class Order extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $table = '__QT_ORDER__';
    protected $name = 'qt_order';
    protected $pk = 'id';
    protected $autoWriteTimestamp = true;


    /**
     * 项目下单
     * @param $data
     */
    public function create_order($data, $userInfo)
    {
        if(!isset($data['creater_room'])){
            $data['creater_room'] = '';
        }
        $projectRes = Db::name('qt_project')->where('id', $data['project_id'])->find();
        $totalNum = $data['man_num'] + $data['woman_num'] + $data['other_num'];
        $totalPrice = bcmul($projectRes['price'], $totalNum, 2);
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $data['room_id'], 'pay_status' => '1'])->find();
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $projectRes['store_id'];
            $order['room_id'] = $data['room_id'];
            $order['hand_card_id'] = $data['hand_card_id'];
            $order['total_num'] = $totalNum;
            $order['total_price'] = $totalPrice;
            $order['status'] = '1';
            $order['delay'] = $data['delay'];
            $order['time_type'] = $data['time_type'];
            $order['created_time'] = time();
            $orderRes = self::create($order);
            $orderId = $orderRes->id;
        } else {
            $orderId = $orderCheck['id'];
        }
        //轮排订单
        if ($data['order_type'] == '1') {
            try {
                $orderProject = [];
                //生成订单附表
                for ($i = 0; $i < $totalNum; $i++) {
                    $orderProject[$i] = [
                        'name' => $projectRes['name'],
                        'created_order_id' => $data['create_id'],
                        'creater_room' => $data['creater_room'],
                        'order_id' => $orderId,
                        'project_id' => $data['project_id'],
                        'room_id' => $data['room_id'],
                        'hand_card_id' => $data['hand_card_id'],
                        'order_type' => $data['order_type'],
                        'num' => '1',
                        'price' => $projectRes['price'],
                        'store_id' => $projectRes['store_id'],
                        'create_id' => $data['create_id'],
                        'sale_id' => $data['sale_id'],
                        'created_time' => time(),
                    ];
                }
                Db::name('qt_order_project')->insertAll($orderProject);
                $project = Db::name('qt_order_project')->where('is_delete',2)->where('order_id', $orderId)->order('id desc')->limit($totalNum)->select();
                //插入订单详情表
                foreach ($project as $key=>$value){
                    $orderDetailInsert = [
                        'store_id'=>$value['store_id'],
                        'room_id'=>$value['room_id'],
                        'engineer_id'=>'',
                        'hand_card_id'=>$value['hand_card_id'],
                        'check_out_id'=>'',
                        'project_id'=>$value['project_id'],
                        'order_project_id'=>$value['id'],
                        'create_user_id'=>$value['sale_id']?? '',
                        'order_type'=>'1',
                        'create_time'=>time(),
                    ];
                    Db::name('qt_order_detail')->insert($orderDetailInsert);

                }
                //男技师排钟
                if ($data['man_num'] != '0') {
                    $this->calculation($data['room_id'], $data['project_id'], '1', $data['man_num'], $project);
                }
                if ($data['woman_num'] != '0'){
                    //女技师排钟
                    $this->calculation($data['room_id'], $data['project_id'], '2', $data['woman_num'], $project);
                }
                if ($data['other_num'] != '0'){
                    //全部技师排钟
                    $this->calculation($data['room_id'], $data['project_id'], '3', $data['other_num'], $project);
                }
            } catch (Exception $e) {
                print $e->getMessage();
                exit();
            }
            return ['code' => 200, 'msg' => '技师下单成功'];
        } else {
            if(!isset($data['sale_id'])){
                $saleId = $userInfo['id'];
            }else{
                $saleId = $data['sale_id'];
            }
            //点，call钟
            try {
                //生成订单附表
                $orderProject = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $data['create_id'],
                    'creater_room' => $data['creater_room'],
                    'order_id' => $orderId,
                    'engineer_id' => $data['engineer_id'],
                    'project_id' => $data['project_id'],
                    'room_id' => $data['room_id'],
                    'hand_card_id' => $data['hand_card_id'],
                    'order_type' => $data['order_type'],
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'create_id' => $data['create_id'],
                    'created_time' => time(),
                    'sale_id' => $saleId,
                ];
                $order_project_id = Db::name('qt_order_project')->insertGetId($orderProject);
                $project = Db::name('qt_order_project')
                    ->where('is_delete',2)->where('id', $order_project_id)->find();
                $store = Db::name('qt_store')->where('id', $project['store_id'])->find();
                //插入订单详情
                $orderDetailInsert = [
                    'store_id'=>$orderProject['store_id'],
                    'room_id'=>$data['room_id'],
                    'engineer_id'=>$data['engineer_id'],
                    'hand_card_id'=>$data['hand_card_id'],
                    'check_out_id'=>'',
                    'project_id'=>$data['project_id'],
                    'order_project_id'=>$order_project_id,
                    'create_user_id'=>$userInfo['id'],
                    'order_type'=>'1',
                    'create_time'=>time(),
                ];
                Db::name('qt_order_detail')->insert($orderDetailInsert);
                //给技师排班
                $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$store['id'],'many_project_id'=>$data['project_id']])->find();
                if(empty($findManyQueue)){
                    $this->scheduling($project, '4', $store, $data['engineer_id']);
                }else{
                    $this->many_scheduling($project, '4', $store,$findManyQueue['many_queue_id'],$data['engineer_id']);
                }
            } catch (Exception $e) {
                print $e->getMessage();
                exit();
            }
            return ['code' => 200, 'msg' => '技师下单成功'];
        }
    }


    /**
     * app项目下单
     * @param $data
     */
    public function create_app_order($data, $userInfo)
    {
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $data['room_id'], 'pay_status' => '1'])->find();
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $userInfo['store_id'];
            $order['room_id'] = $data['room_id'];
            $order['hand_card_id'] = $data['hand_card_id'];
            $order['total_num'] = $data['total_num'];
            $order['total_price'] = $data['total_price'];
            $order['status'] = '1';
            $order['order_type'] = $data['order_type'];
            $order['delay'] = $data['delay'];
            $order['time_type'] = $data['time_type'];
            $order['created_time'] = time();
            $orderRes = self::create($order);
            $orderId = $orderRes->id;
        } else {
            $orderId = $orderCheck['id'];
        }

        //轮排订单
        if ($data['order_type'] == '1') {
            $projectData = json_decode($data['project'], true);
            foreach ($projectData as $key => $value) {
                $projectRes = Db::name('qt_project')->where('id', $value['project_id'])->find();
                try {
                    //生成订单附表
                    for ($i = 0; $i < $value['num']; $i++) {
                        $orderProject[$i] = [
                            'name' => $projectRes['name'],
                            'created_order_id' => $data['create_id'],
                            'order_id' => $orderId,
                            'project_id' => $value['project_id'],
                            'room_id' => $data['room_id'],
                            'hand_card_id' => $data['hand_card_id'],
                            'order_type' => $data['order_type'],
                            'num' => '1',
                            'price' => $projectRes['price'],
                            'store_id' => $projectRes['store_id'],
                            'creater_room' => $data['creater_room']?? '',
                            'sale_id' => $data['sale_id'],
                            'created_time' => time(),
                        ];
                    }
                    Db::name('qt_order_project')->insertAll($orderProject);
                    $project = Db::name('qt_order_project')
                        ->where('is_delete',2)->where('order_id', $orderId)
                        ->order('id desc')
                        ->limit($value['num'])
                        ->select();
                    //插入订单详情表
                    foreach ($project as $k=>$v){
                        $orderDetailInsert = [
                            'store_id'=>$v['store_id'],
                            'room_id'=>$v['room_id'],
                            'engineer_id'=>'',
                            'hand_card_id'=>$v['hand_card_id'],
                            'check_out_id'=>'',
                            'project_id'=>$v['project_id'],
                            'order_project_id'=>$v['id'],
                            'create_user_id'=>$v['sale_id']?? '',
                            'order_type'=>'1',
                            'create_time'=>time(),
                        ];
                        Db::name('qt_order_detail')->insert($orderDetailInsert);
                    }
                    //男技师排钟
                    if (strval($value['man_num']) != '') {
                        $this->calculation($data['room_id'], $value['project_id'], '1', $value['man_num'], $project);
                    }
                    //女技师排钟
                    if (strval($value['woman_num']) != '') {
                        $this->calculation($data['room_id'], $value['project_id'], '2', $value['woman_num'], $project);
                    }
                    //全部技师排钟
                    if (strval($data['other_num'])  != '') {
                        $this->calculation($data['room_id'], $value['project_id'], '3', $value['other_num'], $project);
                    }
                } catch (Exception $e) {
                    print $e->getMessage();
                    exit();
                }
            }
            return ['code' => 200, 'msg' => '技师下单成功'];
        } else {
            return ['code' => 204, 'msg' => '无效的请求方式'];
        }
    }


    /**
     * 待安排项目下单
     * @param $data
     */
    public function room_order($data, $engineer)
    {
        $projectRes = Db::name('qt_project')->where('id', $data['project_id'])->find();
        $totalPrice = bcmul($projectRes['price'], $data['number'], 2);
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $data['room_id'], 'pay_status' => '1'])->find();
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $data['store_id'];
            $order['room_id'] = $data['room_id'];
            $order['total_num'] = $data['number'];
            $order['total_price'] = $totalPrice;
            $order['status'] = '1';
            $order['order_type'] = '1';
            $order['delay'] = 0;
            $order['time_type'] = '1';
            $order['created_time'] = time();
            $orderRes = self::create($order);
            $orderId = $orderRes->id;
        } else {
            $orderId = $orderCheck['id'];
        }
        $engineerIds = explode(',', $engineer);
        //轮排订单
        try {
            //生成订单附表
            for ($i = 0; $i < count($engineerIds); $i++) {
                $userInfo = Db::name('qt_users')->where('id', $engineerIds[$i])->find();
                //判断是否加班
                if ($userInfo['is_add'] == '2') {
                    $add = '2';//加班
                } else {
                    $add = '1';//正常班
                }
                $orderProject[$i] = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $data['create_id'],
                    'order_id' => $orderId,
                    'project_id' => $data['project_id'],
                    'room_id' => $data['room_id'],
                    'order_type' => '1',
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'creater_room' => $data['creater_room'],
                    'sale_id' => $userInfo['id'],
                    'created_time' => time(),
                    'is_add' => $add,
                ];
            }
            Db::name('qt_order_project')->insertAll($orderProject);
            //安排技师
            for ($i = 0; $i < count($engineerIds); $i++) {
                //判断当前技师是否在上钟
                $engineerRes = Db::name('qt_users')->where('id', $engineerIds[$i])->find();
                if ($engineerRes['work_status'] != '1') {
                    return ['code' => 204, 'msg' => '该技师未处于空闲状态'];
                }
                $orderData = Db::name('qt_order_project')
                    ->where('is_delete',2)->where('order_id', $orderId)->select();
                $order = $orderData[$i];
                //更新订单中的技师
                Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $engineerIds[$i], 'is_add' => $add]);
                //更新房间等待数量
                Db::name('qt_wait')->where('id', $data['id'])->setDec('number', '1');
                //更新用户信息
                Db::name('qt_users')->where('id', $engineerIds[$i])->update(['work_status' => '5', 'room_id' => $order['room_id']]);
                //更新房间订单号
                Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
                $updateQueue['room_id'] = $order['room_id'];
                $updateQueue['project_id'] = $order['project_id'];
                $updateQueue['order_project_id'] = $order['id'];
                $updateQueue['order_user_id'] = $order['created_order_id'];
                $updateQueue['day'] = date("Y-m-d");
                $updateQueue['type_id'] = $userInfo['work_type'];
                $updateQueue['status'] = '2';
                //判断上班点钟是否动牌
                $storeQueueValue = Db::name('qt_queue_rule')->where(['store_id' => $data['store_id'], 'type' => '1'])->find();
                //找到最后一个技师
                $endSort = Db::name('qt_order_queue')
                    ->where(['store_id' => $order['store_id']])
                    ->order('sort desc')
                    ->find();
                if ($add == '1') {
                    $updateQueue['sort'] = $endSort['sort'] + 1;
                } else {
                    //判断加班点钟是否动牌
                    if ($storeQueueValue['is_overtime_dot_act'] == '1' && $order['order_type'] == '2') {
                        $updateQueue['sort'] = $endSort['sort'] + 1;
                    } else {
                        $updateQueue['sort'] = $endSort['sort'] + 1;
                    }
                }
                Db::name('qt_order_queue')->where(['user_id' => $engineerRes['id']])->update($updateQueue);
                //更新提成信息
                $commission = 0;
                //普通提成
                if ($order['is_add'] == '1') {
                    $commission = new OrdinaryService();
                    $commission = $commission->showCommission($order['order_type'], $order['is_add'], $projectRes);
                }
                //加班提成
                if ($order['is_add'] == '2') {
                    $commission = new AddService();
                    $commission = $commission->showCommission($order['order_type'], $order['is_add'], $projectRes);
                }
                //计算接待提成
                $receiver = new ReceiverService();
                $receiver = $receiver->showCommission($order['order_type'], $order['is_add'], $projectRes);
                $floor_commission_type = Db::name('qt_store')->where(['id'=>$order['store_id']])->value('floor_commission_type');
                if ($floor_commission_type == '1') {
                    $cashierId = $data['create_id'];
                } else {
                    $cashierId = $data['creater_room'];
                }
                $insert = [
                    'store_id' => $order['store_id'],
                    'user_id' => $engineerIds[$i],
                    'cashier_id' => $cashierId,//接待人
                    'room_id' => $order['room_id'],
                    'money' => $order['price'],
                    'commission' => $commission,//技师提成
                    'receiver' => $receiver,//接待提成
                    'product_id' => $order['project_id'],
                    'type' => '1',
                    'created_time' => time(),
                    'is_pay' => '1',
                    'order_project_id' => $order['id'],
                    'status' => $order['order_type'],
                    'is_add' => $order['is_add'],
                ];
                Db::name('qt_commission_log')->insert($insert);
                Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['commission'=>$commission,'receiver'=>$receiver]);
            }
        } catch (Exception $e) {
            print $e->getMessage();
            exit();
        }
        return ['code' => 200, 'msg' => '技师下单成功'];
    }


    /**
     * 计算技师缺少和排钟
     * @param $room_id [房间ID]
     * @param $project_id [项目ID]
     * @param $sex [性别 1 男 2 女 3 其他]
     * @param $number [数量]
     */
    public function calculation($room_id, $project_id, $sex, $number, $orderProject)
    {
        $number = intval($number);
        $storeId = Db::name('qt_room')->where('id', $room_id)->value('store_id');
        $storeRes = Db::name('qt_store')->where('id', $storeId)->find();
        //查询男女技师数量
        $man = Db::name('qt_user_project')
            ->field('p.id as project_id,u.real_name')
            ->alias('p')
            ->leftJoin('qt_users u', 'u.id = p.engineer_id')
            ->where('p.project_id', $project_id)
            ->where(['u.work_status' => '1', 'u.sex' => '1', 'u.status' => '0', 'u.store_id' => $storeId])
            ->count();
        $girl = Db::name('qt_user_project')
            ->field('p.id as project_id,u.real_name')
            ->alias('p')
            ->leftJoin('qt_users u', 'u.id = p.engineer_id')
            ->where('p.project_id', $project_id)
            ->where(['u.work_status' => '1', 'u.sex' => '2', 'u.status' => '0', 'u.store_id' => $storeId])
            ->count();
        //男技师
        if ($sex == '1') {
            if ($man < $number) {
                $wait = $number - $man;
                $j = $man;
                //插入技师等待列表
                for ($i = 1; $i <= $wait; $i++) {
                    Db::name('qt_wait')->insert([
                        'store_id' => $storeId,
                        'order_id' => $orderProject[$j]['id'],
                        'engineer_id' => '',
                        'status' => '1',
                        'project_id' => $project_id,
                        'room_id' => $room_id,
                        'sex' => '1',
                        'create_id' => $orderProject[$j]['created_order_id'],
                        'create_time' => time(),
                    ]);
                    $j++;
                }
                //给有的技师安排
                for ($i = 1; $i <= $man; $i++) {
                    //给技师排班
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }
            } else {
                for ($i = 1; $i <= $number; $i++) {
                    //给技师排班
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }
            }
        } elseif ($sex == '2') {
            //女技师排班
            if ($girl < $number) {
                $wait = $number - $girl;
                $j = $girl;
                //插入技师等待列表
                for ($i = 1; $i <= $wait; $i++) {
                    Db::name('qt_wait')->insert([
                        'store_id' => $storeId,
                        'order_id' => $orderProject[$j]['id'],
                        'engineer_id' => '',
                        'status' => '1',
                        'project_id' => $project_id,
                        'room_id' => $room_id,
                        'sex' => '2',
                        'create_id' => $orderProject[$j]['created_order_id'],
                        'create_time' => time(),
                    ]);
                    $j++;
                }
                //给有的技师安排
                for ($i = 1; $i <= $girl; $i++) {
                    //给技师排班
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }
            } else {
                for ($i = 1; $i <= $number; $i++) {
                    //给技师排班
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }

            }
        } else {
            //其他技师
            if (($man + $girl) < $number) {
                $wait = $number - ($man + $girl);
                $j = ($man + $girl);
                //插入技师等待列表
                for ($i = 1; $i <= $wait; $i++) {
                    Db::name('qt_wait')->insert([
                        'store_id' => $storeId,
                        'order_id' => $orderProject[$j]['id'],
                        'engineer_id' => '',
                        'status' => '1',
                        'project_id' => $project_id,
                        'room_id' => $room_id,
                        'sex' => '3',
                        'create_id' => $orderProject[$j]['created_order_id'],
                        'create_time' => time(),
                    ]);
                    $j++;
                }
                //给有的技师安排
                for ($i = 1; $i <= ($man + $girl); $i++) {
                    //给技师排班
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }
            } else {
                for ($i = 1; $i < $number; $i++) {
                    $findManyQueue = Db::name('qt_order_many_queue')->where(['store_id'=>$storeId,'many_project_id'=>$orderProject[$i-1]['project_id']])->find();
                    if(empty($findManyQueue)){
                        $this->scheduling($orderProject[$i - 1], $sex, $storeRes);
                    }else{
                        $this->many_scheduling($orderProject[$i - 1], $sex, $storeRes,$findManyQueue['many_queue_id']);
                    }
                }
            }
        }

    }


    /**
     * 订单派技师
     * @param $order [订单信息]
     * @param $type [订单类型]
     */
    public function scheduling($order, $sex, $store, $engineer = '')
    {
        if ($sex == '3') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
        } elseif ($sex == '1') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
        } elseif ($sex == '2') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
        } elseif ($sex == '4') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.status' => '0', 'u.store_id' => $store['id']]);
        }
        //新增优先排钟规则
        $rowClock = Db::name('qt_row_clock')->where(['project_id' => $order['project_id'], 'store_id' => $store['id']])->find();
        $newEmpty = 0;
        if (!empty($rowClock)) {
            $newEmpty = 1;
            $typeId = explode(',', $rowClock['work_types']);
            $sql->whereIn('u.top_type_id', $typeId);
            $userIds = $sql->group('up.engineer_id')->column('up.engineer_id');
            if (empty($userIds)) {
                //如果没有当班技师查找其他的技师
                if ($sex == '3') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
                } elseif ($sex == '1') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
                } elseif ($sex == '2') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id']]);
                } elseif ($sex == '4') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.status' => '0', 'u.store_id' => $store['id']]);
                }
                $userIds = $emptySql->group('up.engineer_id')->column('up.engineer_id');
            }
        } else {
            $userIds = $sql->group('up.engineer_id')->column('up.engineer_id');
        }
        //获取可做项目的所有空闲技师
        if (empty($userIds)) {
            Db::name('qt_wait')->insert([
                'store_id' => $store['id'],
                'order_id' => $order['id'],
                'engineer_id' => '',
                'status' => '1',
                'project_id' => $order['project_id'],
                'room_id' => $order['room_id'],
                'sex' => $sex,
                'create_id' => $order['created_order_id'],
                'create_time' => time(),
            ]);
            return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
        }
        $value = Db::name('qt_queue_rule')->where(['type' => '1', 'store_id' => $store['id']])->find();
        $endSort = Db::name('qt_order_queue')
            ->where(['store_id' => $order['store_id']])
            ->order('sort desc')
            ->find();
        if ($order['order_type'] == '1') {
            //查找技师中是否有头牌技师，如果有头牌优先安排头牌技师
            $topData = Db::name('qt_top_card')
                ->whereIn('engineer_id', $userIds)
                ->where('end_time', '>', time())
                ->where('is_use', '0')
                ->order('id asc')
                ->find();
            if (!empty($topData)) {
                //有头牌优先安排头牌技师
                $empty = Db::name('qt_order_queue')
                    ->field('oq.*,u.work_type')
                    ->alias('oq')
                    ->leftJoin('qt_users u', 'u.id = oq.user_id')
                    ->where('oq.user_id', $topData['engineer_id'])
                    ->find();
            } else {
                $sql = Db::name('qt_order_queue')
                    ->field('oq.*,u.work_type')
                    ->alias('oq')
                    ->leftJoin('qt_users u', 'u.id = oq.user_id')
                    ->whereIn('oq.user_id', $userIds)
                    ->where('u.work_status', '1');
                /*******增加技师排位限制*****************/
                if(!empty($value)){
                    //优先排当班技师
                    if($value['is_working_engineer_first'] == '1'){
                        $sql->where('u.is_add','1');
                    }
                    $empty = $sql->order('oq.sort asc')->find();
                    //如果无当班技师安排其他班次技师
                    if(empty($empty)){
                        $empty = Db::name('qt_order_queue')
                            ->field('oq.*,u.work_type')
                            ->alias('oq')
                            ->leftJoin('qt_users u', 'u.id = oq.user_id')
                            ->whereIn('oq.user_id', $userIds)
                            ->where('u.work_status', '1')
                            ->order('oq.sort asc')
                            ->find();
                        if(empty($empty)){
                            Db::name('qt_wait')->insert([
                                'store_id' => $store['id'],
                                'order_id' => $order['id'],
                                'engineer_id' => '',
                                'status' => '1',
                                'project_id' => $order['project_id'],
                                'room_id' => $order['room_id'],
                                'sex' => $sex,
                                'create_id' => $order['created_order_id'],
                                'create_time' => time(),
                            ]);
                            return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
                        }
                    }
                }else{
                    $empty = $sql->order('oq.sort asc')->find();
                }
            }
            //判断技师是否有退换时间
            if ($empty['return_time'] != null) {
                $time = (time() - $empty['return_time']) / 60;
                $time = floor($time);
                //有退钟时间并且是当前的房间退钟，判断十五分钟
                if ($time < $store['interval_time'] && $order['room_id'] == $empty['return_room']) {
                    $empty = $sql->whereNull('oq.return_time')->order('oq.sort asc')->find();
                    if (empty($empty)) {
                        Db::name('qt_wait')->insert([
                            'store_id' => $store['id'],
                            'order_id' => $order['id'],
                            'engineer_id' => '',
                            'status' => '1',
                            'project_id' => $order['project_id'],
                            'room_id' => $order['room_id'],
                            'sex' => $sex,
                            'create_id' => $order['created_order_id'],
                            'create_time' => time(),
                        ]);
                        return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
                    }
                }
            }
            $isAdd = Db::name('qt_users')->where('id', $empty['user_id'])->value('is_add');
            //加班是否自动排钟
            if($value['is_overtime_auto_queue'] == '0' && $isAdd == '2'){
                Db::name('qt_wait')->insert([
                    'store_id' => $store['id'],
                    'order_id' => $order['id'],
                    'engineer_id' => '',
                    'status' => '1',
                    'project_id' => $order['project_id'],
                    'room_id' => $order['room_id'],
                    'sex' => $sex,
                    'create_id' => $order['created_order_id'],
                    'create_time' => time(),
                ]);
                return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
            }
            try {
                Db::startTrans();
                //更新头牌数据
                if (!empty($topData) && $topData['rule'] == '1') {
                    //更新头牌信息
                    Db::name('qt_top_card')->where('id', $topData['id'])->update(['is_use' => '1']);
                }
                //修改订单状态
                Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $empty['user_id'], 'return_time' => null, 'is_add' => $isAdd]);
                Db::name('qt_order_detail')->where(['order_project_id' => $order['id'],'order_type'=>'1'])->update(['engineer_id' => $empty['user_id']]);
                //更新技师状态
                Db::name('qt_users')->where('id', $empty['user_id'])->update(['work_status' => '5', 'room_id' => $order['room_id']]);
                //更新房间订单号
                Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
                //更新当前技师的排钟
                $updateQueue['room_id'] = $order['room_id'];
                $updateQueue['project_id'] = $order['project_id'];
                $updateQueue['order_project_id'] = $order['id'];
                $updateQueue['order_user_id'] = $order['created_order_id'];
                $updateQueue['day'] = date("Y-m-d");
                $updateQueue['type_id'] = $empty['work_type'];
                $updateQueue['status'] = '2';
                $updateQueue['sort'] = $endSort['sort'] + 1;
                $updateQueue['old_sort'] = $empty['sort'];
                //优先排钟规则其他技师是否动排
                if ($newEmpty == 1 && !empty($rowClock)) {
                    if ($rowClock['no_first'] == '1') {
                        unset($updateQueue['sort']);
                    }
                }
                //下钟动排
                if($value['is_down_act'] == '1'){
                    unset($updateQueue['sort']);
                }
                //副项是否自动排钟
                $projectType = Db::name('qt_order_project')
                    ->alias('o')
                    ->leftJoin('qt_project p','o.project_id = p.id')
                    ->where(['o.id'=>$order['id']])->value('p.type');
                if($value['second_act_type'] != '1' && $projectType == '2'){
                    unset($updateQueue['sort']);
                }
                Db::name('qt_order_queue')->where(['user_id' => $empty['user_id']])->update($updateQueue);
                Duanwei::DuanweiPrice($empty['user_id'],$order['project_id'],$order['room_id']);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                return ['code' => 204, 'msg' => '技师排班失败'];
            }
        } else {
            $engineerInfo =  Db::name('qt_users')->where('id', $engineer)->find();
            if(in_array($engineerInfo['work_status'],[1,3]) == false){
                return ['code' => 204, 'msg' => '当前技师不是空闲状态'];
            }
            $isAdd = $engineerInfo['is_add'];
            Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $engineer, 'is_add' => $isAdd]);
            Db::name('qt_order_detail')->where(['order_project_id' => $order['id'],'order_type'=>'1'])->update(['engineer_id' =>$engineer]);
            Db::name('qt_users')->where('id', $engineer)->update(['work_status' => '5', 'room_id' => $order['room_id']]);
            //更新房间订单号
            Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
            $empty = Db::name('qt_order_queue')
                ->field('oq.*,u.work_type')
                ->alias('oq')
                ->leftJoin('qt_users u', 'u.id = oq.user_id')
                ->where('u.id', $engineer)
                ->find();
            $updateQueue['room_id'] = $order['room_id'];
            $updateQueue['project_id'] = $order['project_id'];
            $updateQueue['order_project_id'] = $order['id'];
            $updateQueue['order_user_id'] = $order['created_order_id'];
            $updateQueue['day'] = date("Y-m-d");
            $updateQueue['type_id'] = $empty['work_type'];
            $updateQueue['status'] = '2';
            //判断上班点钟是否动牌
            if ($isAdd == '1') {
                if ($value['is_working_dot_act'] == '1' && $order['order_type'] == '2') {
                    $updateQueue['sort'] = $endSort['sort'] + 1;
                }
            } else {
                //判断加班点钟是否动牌
                if ($value['is_overtime_dot_act'] == '1' && $order['order_type'] == '2') {
                    $updateQueue['sort'] = $endSort['sort'] + 1;
                }
            }
            //下钟动排
            if($value['is_down_act'] == '1'){
                unset($updateQueue['sort']);
            }
            //副项是否自动排钟
            $projectType = Db::name('qt_order_project')
                ->alias('o')
                ->leftJoin('qt_project p','o.project_id = p.id')
                ->where(['o.id'=>$order['id']])->value('p.type');
            if($value['second_act_type'] != '1' && $projectType == '2'){
                unset($updateQueue['sort']);
            }
            Duanwei::DuanweiPrice($engineer,$order['project_id'],$order['room_id']);
            Db::name('qt_order_queue')->where(['user_id' => $empty['user_id']])->update($updateQueue);
        }
        //更新提成信息
        $project = Db::name('qt_project')->where('id', $order['project_id'])->find();
        $commission = 0;
        //普通提成
        if ($isAdd == '1') {
            $commission = new OrdinaryService();
            $commission = $commission->showCommission($order['order_type'], $isAdd, $project);
        }
        //加班提成
        if ($isAdd == '2') {
            $commission = new AddService();
            $commission = $commission->showCommission($order['order_type'], $isAdd, $project);
        }
        //计算接待提成
        $receiver = new ReceiverService();
        $receiver = $receiver->showCommission($order['order_type'], $isAdd, $project);
        if($engineer != ''){
            $user_id = $engineer;
        }else{
            $user_id = $empty['user_id'];
        }
        $insert = [
            'store_id' => $store['id'],
            'cashier_id' => $order['sale_id'],//接待人
            'user_id' => $user_id,//技师
            'room_id' => $order['room_id'],
            'money' => $order['price'],
            'commission' => $commission,//技师提成
            'receiver' => $receiver,//接待提成
            'product_id' => $order['project_id'],
            'type' => '1',
            'created_time' => time(),
            'is_pay' => '1',
            'order_project_id' => $order['id'],
            'status' => $order['order_type'],
            'is_add' => $isAdd,
        ];
        Db::name('qt_commission_log')->insert($insert);
        //更新订单提成
        Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['commission'=>$commission,'receiver'=>$receiver]);
        return ['code' => 200, 'msg' => '技师排班成功'];
    }


    /**
     * 订单派技师
     * @param $order [订单信息]
     * @param $type [订单类型]
     */
    public function engineerScheduling($order, $store, $engineer = '')
    {
        //技师排钟规则
        $value = Db::name('qt_queue_rule')->where(['type' => '1', 'store_id' => $store['id']])->find();
        //最后以为技师排序值
        $endSort = Db::name('qt_order_queue')
            ->where(['store_id' => $order['store_id']])
            ->order('sort desc')
            ->max('sort');
        //项目信息
        $project = Db::name('qt_project')->where('id', $order['project_id'])->find();
        //技师上班状态（正常或者加班）
        $isAdd = Db::name('qt_users')->where('id', $engineer)->value('is_add');
        //更新项目订单
        Db::name('qt_order_project')->where(['id' => $order['id']])
            ->update([
                'engineer_id' => $engineer,
                'is_add' => $isAdd,
                'start_time' => time(),
                'end_time' => time() + ($project['time'] * 60),
                'status'=>'2'
            ]);
        //更新技师状态
        Db::name('qt_users')->where('id', $engineer)->update(['work_status' => '4', 'room_id' => $order['room_id']]);
        //更新房间订单号
        Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '3']);
        //技师排班信息
        $engineerQueue = Db::name('qt_order_queue')
            ->field('oq.*,u.work_type')
            ->alias('oq')
            ->leftJoin('qt_users u', 'u.id = oq.user_id')
            ->where('u.id', $engineer)
            ->find();
        //技师信息更新
        $updateQueue['room_id'] = $order['room_id'];
        $updateQueue['project_id'] = $order['project_id'];
        $updateQueue['order_project_id'] = $order['id'];
        $updateQueue['order_user_id'] = $order['created_order_id'];
        $updateQueue['day'] = date("Y-m-d");
        $updateQueue['type_id'] = $engineerQueue['work_type'];
        $updateQueue['status'] = '3';
        $updateQueue['start_time'] = time();
        $updateQueue['end_time'] = time() + ($project['time'] * 60);
        //判断上班点钟是否动牌
        if ($isAdd == '1') {
            if ($value['is_working_dot_act'] == '1' && $order['order_type'] == '2') {
                $updateQueue['sort'] = $endSort + 1;
            }
        } else {
            //判断加班点钟是否动牌
            if ($value['is_overtime_dot_act'] == '1' && $order['order_type'] == '2') {
                $updateQueue['sort'] = $endSort + 1;
            }
        }
        Db::name('qt_order_queue')->where(['user_id' => $engineerQueue['user_id']])->update($updateQueue);
        //更新提成信息
        $commission = 0;
        //普通提成
        if ($order['is_add'] == '1') {
            $commission = new OrdinaryService();
            $commission = $commission->showCommission($order['order_type'], $order['is_add'], $project);
        }
        //加班提成
        if ($order['is_add'] == '2') {
            $commission = new AddService();
            $commission = $commission->showCommission($order['order_type'], $order['is_add'], $project);
        }
        //计算接待提成
        $receiver = new ReceiverService();
        $receiver = $receiver->showCommission($order['order_type'], $isAdd, $project);
        $insert = [
            'store_id' => $store['id'],
            'user_id' => $engineer,
            'cashier_id' => $order['sale_id'],
            'room_id' => $order['room_id'],
            'money' => $order['price'],
            'commission' => $commission,
            'receiver' => $receiver,
            'product_id' => $order['project_id'],
            'type' => '1',
            'created_time' => time(),
            'is_pay' => '1',
            'order_project_id' => $order['id'],
            'status' => $order['order_type'],
            'is_add' => $order['is_add'],
        ];
        Db::name('qt_commission_log')->insert($insert);
        return ['code' => 200, 'msg' => '技师排班成功'];
    }


    /**
     * app点钟call钟选钟项目下单
     * @param $data
     */
    public function app_order($data, $userInfo)
    {
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $data['room_id'], 'pay_status' => '1'])->find();
        $data['project'] = json_decode($data['project'], true);
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $userInfo['store_id'];
            $order['room_id'] = $data['room_id'];
            $order['hand_card_id'] = $data['hand_card_id'];
            $order['total_num'] = count($data['project']);
            $order['total_price'] = $data['total_price'];
            $order['status'] = '1';
            $order['order_type'] = $data['order_type'];
            $order['delay'] = $data['delay'];
            $order['time_type'] = $data['time_type'];
            $order['created_time'] = time();
            $orderRes = self::create($order);
            $orderId = $orderRes->id;
        } else {
            $orderId = $orderCheck['id'];
        }
        foreach ($data['project'] as $key => $value) {
            $projectRes = Db::name('qt_project')->where(['id' => $value['project_ids']])->find();
            //点，call钟
            try {
                //生成订单附表
                $orderProject = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $data['create_id'],
                    'order_id' => $orderId,
                    'engineer_id' => $value['user_id'],
                    'project_id' => $value['project_ids'],
                    'room_id' => $data['room_id'],
                    'hand_card_id' => $data['hand_card_id'],
                    'order_type' => $data['order_type'],
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'creater_room' => $data['creater_room'],
                    'created_time' => time(),
                    'sale_id' => $data['sale_id'],
                ];
                $orderProjectID = Db::name('qt_order_project')->insertGetId($orderProject);
                $project = Db::name('qt_order_project')->where('id', $orderProjectID)->find();
                $store = Db::name('qt_store')->where('id', $project['store_id'])->find();
                $this->scheduling($project, '4', $store, $value['user_id']);
            } catch (Exception $e) {
                print $e->getMessage();
                exit();
            }

        }
        return ['code' => 200, 'msg' => '技师下单成功'];

    }


    /**
     * 延迟项目下单
     * @param $data
     */
    public function delay_order($data, $userInfo)
    {
        $projectRes = Db::name('qt_project')->where('id', $data['project_id'])->find();
        $totalNum = $data['man_num'] + $data['woman_num'] + $data['other_num'];
        $totalPrice = bcmul($projectRes['price'], $totalNum, 2);
        //判断当前房间是否有未结账订单
        $orderCheck = Db::name('qt_order')->where(['room_id' => $data['room_id'], 'pay_status' => '1'])->find();
        if (empty($orderCheck)) {
            $order['order_no'] = ordersn();
            $order['store_id'] = $projectRes['store_id'];
            $order['room_id'] = $data['room_id'];
            $order['hand_card_id'] = $data['hand_card_id'];
            $order['total_num'] = $totalNum;
            $order['total_price'] = $totalPrice;
            $order['status'] = '1';
            $order['delay'] = $data['delay'];
            $order['time_type'] = $data['time_type'];
            $order['created_time'] = time();
            $orderRes = self::create($order);
            $orderId = $orderRes->id;
        } else {
            $orderId = $orderCheck['id'];
        }
        try {
            //生成订单附表
            for ($i = 0; $i < $totalNum; $i++) {
                //判断是否加班
                if ($userInfo['is_add'] == '2') {
                    $add = '2';//加班
                } else {
                    $add = '1';//正常班
                }
                $orderProject[$i] = [
                    'name' => $projectRes['name'],
                    'created_order_id' => $data['create_id'],
                    'order_id' => $orderId,
                    'project_id' => $data['project_id'],
                    'room_id' => $data['room_id'],
                    'hand_card_id' => $data['hand_card_id'],
                    'order_type' => $data['order_type'],
                    'num' => '1',
                    'price' => $projectRes['price'],
                    'store_id' => $projectRes['store_id'],
                    'creater_room' => $data['create_id'],
                    'sale_id' => $userInfo['id'],
                    'created_time' => time(),
                    'is_add' => $add,
                ];
            }
            Db::name('qt_order_project')->insertAll($orderProject);
            $project = Db::name('qt_order_project')->where('order_id', $orderId)->select();
            //男技师排钟
            if ($data['man_num'] != '0') {
                $this->calculation($data['room_id'], $data['project_id'], '1', $data['man_num'], $project);
            }
            //女技师排钟
            if ($data['woman_num'] != '0') {
                $this->calculation($data['room_id'], $data['project_id'], '2', $data['woman_num'], $project);
            }
            //全部技师排钟
            if ($data['other_num'] != '0') {
                $this->calculation($data['room_id'], $data['project_id'], '3', $data['other_num'], $project);
            }
        } catch (Exception $e) {
            print $e->getMessage();
            exit();
        }
        return ['code' => 200, 'msg' => '技师下单成功'];

    }


    /**
     * 多种排位订单派技师
     * @param $order [订单信息]
     * @param $type [订单类型]
     */
    public function many_scheduling($order, $sex, $store,$manyQueueId,$engineer = '')
    {
        if ($sex == '3') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
        } elseif ($sex == '1') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
        } elseif ($sex == '2') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
        } elseif ($sex == '4') {
            $sql = Db::name('qt_user_project')
                ->alias('up')
                ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                ->where('up.project_id', $order['project_id'])
                ->where(['u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId,'u.id'=>$engineer]);
        }
        //新增优先排钟规则
        $rowClock = Db::name('qt_row_clock')->where(['project_id' => $order['project_id'], 'store_id' => $store['id']])->find();
        $newEmpty = 0;
        if (!empty($rowClock)) {
            $newEmpty = 1;
            $typeId = explode(',', $rowClock['work_types']);
            $sql->whereIn('u.top_type_id', $typeId);
            $userIds = $sql->group('up.engineer_id')->column('up.engineer_id');
            if (empty($userIds)) {
                $newEmpty = 1;
                //如果没有当班技师查找其他的技师
                if ($sex == '3') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
                } elseif ($sex == '1') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
                } elseif ($sex == '2') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.work_status' => '1', 'u.sex' => $sex, 'u.status' => '0', 'u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId]);
                } elseif ($sex == '4') {
                    $emptySql = Db::name('qt_user_project')
                        ->alias('up')
                        ->leftJoin('qt_users u', 'u.id = up.engineer_id')
                        ->leftJoin('qt_order_many_queue oq', 'u.id = oq.user_id')
                        ->where('up.project_id', $order['project_id'])
                        ->where(['u.store_id' => $store['id'],'oq.many_queue_id'=>$manyQueueId,'u.id'=>$engineer]);
                }
                $userIds = $emptySql->group('up.engineer_id')->order('oq.sort asc')->column('up.engineer_id');
                if(empty($userIds)){
                    $userIds = $sql->group('up.engineer_id')->order('oq.sort asc')->column('up.engineer_id');
                }
            }
        } else {
            $userIds = $sql->group('up.engineer_id')->order('oq.sort asc')->column('up.engineer_id');
        }
        //获取可做项目的所有空闲技师
        if (empty($userIds)) {
            Db::name('qt_wait')->insert([
                'store_id' => $store['id'],
                'order_id' => $order['id'],
                'engineer_id' => '',
                'status' => '1',
                'project_id' => $order['project_id'],
                'room_id' => $order['room_id'],
                'sex' => $sex,
                'create_id' => $order['created_order_id'],
                'create_time' => time(),
            ]);
            return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
        }
        //查询多种排位规则
        $value = Db::name('qt_many_queue_rule')
            ->where("FIND_IN_SET(" . $order['project_id'] . ",project_ids)")
            ->find();
        //查找技师中是否有头牌技师，如果有头牌优先安排头牌技师
        $topData = Db::name('qt_top_card')
            ->whereIn('engineer_id', $userIds)
            ->where('end_time', '>', time())
            ->where('is_use', '0')
            ->order('id asc')
            ->find();
        if (!empty($topData)) {
            //有头牌优先安排头牌技师
            $empty = Db::name('qt_order_many_queue')
                ->field('oq.*,u.work_type')
                ->alias('oq')
                ->leftJoin('qt_users u', 'u.id = oq.user_id')
                ->where(['oq.user_id'=>$topData['engineer_id'],'oq.many_queue_id'=>$manyQueueId])
                ->find();
        } else {
            $sql = Db::name('qt_order_many_queue')
                ->field('oq.*,u.work_type')
                ->alias('oq')
                ->leftJoin('qt_users u', 'u.id = oq.user_id')
                ->whereIn('oq.user_id', $userIds)
                ->where(['u.work_status'=>'1','oq.many_queue_id'=>$manyQueueId]);
            //查找空闲的技师
            $empty = $sql->order('oq.sort asc')->find();
        }
        //判断技师是否有退换时间
        if ($empty['return_time'] != null) {
            $time = (time() - $empty['return_time']) / 60;
            $time = floor($time);
            //有退钟时间并且是当前的房间退钟，判断十五分钟
            if ($time < $store['back_engineer_block'] && $order['room_id'] == $empty['return_room']) {
                $empty = $sql->whereNull('oq.return_time')->order('oq.sort asc')->find();
                if (empty($empty)) {
                    Db::name('qt_wait')->insert([
                        'store_id' => $store['id'],
                        'order_id' => $order['id'],
                        'engineer_id' => '',
                        'status' => '1',
                        'project_id' => $order['project_id'],
                        'room_id' => $order['room_id'],
                        'sex' => $sex,
                        'create_id' => $order['created_order_id'],
                        'create_time' => time(),
                    ]);
                    return ['code' => 200, 'msg' => '暂无当前技师，已安排等位信息'];
                }
            }
        }
        $isAdd = Db::name('qt_users')->where('id', $empty['user_id'])->value('is_add');
        //加班是否自动排钟
        if($isAdd == '2'  && $value['is_overtime_auto_queue'] == '0'){
            Db::name('qt_wait')->insert([
                'store_id' => $store['id'],
                'order_id' => $order['id'],
                'engineer_id' => '',
                'status' => '1',
                'project_id' => $order['project_id'],
                'room_id' => $order['room_id'],
                'sex' => $sex,
                'create_id' => $order['created_order_id'],
                'create_time' => time(),
            ]);
            return ['code' => 200, 'msg' => '加班无法自动排钟，已安排等位信息'];
        }
        try {
            Db::startTrans();
            //更新头牌数据
            if (!empty($topData) && $topData['rule'] == '1') {
                //更新头牌信息
                Db::name('qt_top_card')->where('id', $topData['id'])->update(['is_use' => '1']);
            }
            //修改订单状态
            Db::name('qt_order_project')->where(['id' => $order['id']])->update(['engineer_id' => $empty['user_id'], 'return_time' => null, 'is_add' => $isAdd]);
            //更新技师状态
            Db::name('qt_users')->where('id', $empty['user_id'])->update(['work_status' => '5', 'room_id' => $order['room_id']]);
            //更新房间订单号
            Db::name('qt_room')->where(['id' => $order['room_id']])->update(['order_id' => $order['order_id'], 'status_id' => '2']);
            //更新当前技师的排钟
            //多种排位
            $endManySort = Db::name('qt_order_many_queue')
                ->where(['many_queue_id' => $manyQueueId])
                ->max('sort');
            //普通排位
            $endSort = Db::name('qt_order_queue')
                ->where(['store_id' => $order['store_id']])
                ->max('sort');
            //更新多重排位数据
            $updateQueue['room_id'] = $order['room_id'];
            $updateQueue['project_id'] = $order['project_id'];
            $updateQueue['order_project_id'] = $order['id'];
            $updateQueue['order_user_id'] = $order['created_order_id'];
            $updateQueue['day'] = date("Y-m-d");
            $updateQueue['type_id'] = $empty['work_type'];
            $updateQueue['status'] = '2';
            $updateQueue['sort'] = $endManySort + 1;

            //更新大轮排数据
            $rowUpdateQueue['room_id'] = $order['room_id'];
            $rowUpdateQueue['project_id'] = $order['project_id'];
            $rowUpdateQueue['order_project_id'] = $order['id'];
            $rowUpdateQueue['order_user_id'] = $order['created_order_id'];
            $rowUpdateQueue['day'] = date("Y-m-d");
            $rowUpdateQueue['type_id'] = $empty['work_type'];
            $rowUpdateQueue['status'] = '2';
            $rowUpdateQueue['sort'] = $endSort + 1;

            //加班排钟是否动排  0 不自动 1 自动
            if (!empty($value)) {
                if ($value['is_overtime_act_queue'] == '0' && $isAdd == '2') {
                    unset($updateQueue['sort']);
                    unset($rowUpdateQueue['sort']);
                }
            }
            //优先排钟规则其他技师是否动排
            if ($newEmpty == 1 && !empty($rowClock)) {
                if ($rowClock['no_first'] == '1') {
                    unset($updateQueue['sort']);
                    unset($rowUpdateQueue['sort']);
                }
            }
            //下钟动排
            if($value['is_down_act'] == '1'){
                unset($updateQueue['sort']);
                unset($rowUpdateQueue['sort']);
            }
            //加班排钟是否动排  0 不自动 1 自动
            if (!empty($value)) {
                if ($value['is_overtime_act_queue'] == '0' && $isAdd == '2') {
                    unset($rowUpdateQueue['sort']);
                    unset($updateQueue['sort']);
                }
            }
            //优先排钟规则其他技师是否动排
            if ($newEmpty == 1 && !empty($rowClock)) {
                if ($rowClock['no_first'] == '1') {
                    unset($rowUpdateQueue['sort']);
                    unset($updateQueue['sort']);
                }
            }

            //判断加班点钟是否动牌
            if ($value['is_overtime_dot_act'] == '1' && $order['order_type'] == '2') {
                $rowUpdateQueue['sort'] = $endSort + 1;
                $updateQueue['sort'] = $endManySort + 1;
            } elseif($order['order_type'] == '2') {
                $rowUpdateQueue['sort'] = $endSort + 1;
                $updateQueue['sort'] = $endManySort+ 1;
            }
            //更新多重排位顺序
            Db::name('qt_order_many_queue')->where(['user_id' => $empty['user_id'],'many_queue_id'=>$manyQueueId])->update($updateQueue);
            //更新排位顺序
            Db::name('qt_order_queue')->where(['user_id' => $empty['user_id']])->update($rowUpdateQueue);
            Duanwei::DuanweiPrice($empty['user_id'],$order['project_id'],$order['room_id']);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            return ['code' => 204, 'msg' => '技师排班失败'];
        }

        //更新提成信息
        $project = Db::name('qt_project')->where('id', $order['project_id'])->find();
        $commission = 0;
        //普通提成
        if ($isAdd == '1') {
            $commission = new OrdinaryService();
            $commission = $commission->showCommission($order['order_type'], $isAdd, $project);
        }
        //加班提成
        if ($isAdd == '2') {
            $commission = new AddService();
            $commission = $commission->showCommission($order['order_type'], $isAdd, $project);
        }
        //计算接待提成
        $receiver = new ReceiverService();
        $receiver = $receiver->showCommission($order['order_type'], $isAdd, $project);
        if($engineer != ''){
            $user_id = $engineer;
        }else{
            $user_id = $empty['user_id'];
        }
        $insert = [
            'store_id' => $store['id'],
            'cashier_id' => $order['sale_id'],//接待人
            'user_id' => $user_id,//技师
            'room_id' => $order['room_id'],
            'money' => $order['price'],
            'commission' => $commission,//技师提成
            'receiver' => $receiver,//接待提成
            'product_id' => $order['project_id'],
            'type' => '1',
            'created_time' => time(),
            'is_pay' => '1',
            'order_project_id' => $order['id'],
            'status' => $order['order_type'],
            'is_add' => $isAdd,
        ];
        Db::name('qt_commission_log')->insert($insert);
        //更新订单提成
        Db::name('qt_order_project')->where(['id'=>$order['id']])->update(['commission'=>$commission,'receiver'=>$receiver]);
        return ['code' => 200, 'msg' => '技师排班成功'];
    }


}